package com.example.springboot3.controller;

import com.example.springboot3.common.Result;
import com.example.springboot3.common.enums.RoleEnum;
import com.example.springboot3.entity.Account;
import com.example.springboot3.entity.Admin;
import com.example.springboot3.service.AdminService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin")
public class AdminController {

//  controller层，接收前端数据，调用service层方法，返回数据给前端,service层调用mapper层方法，操作数据库
//  要用service层，就得用Resource注解
//    传进去的是什么 返回的是什么
    @Resource
    private AdminService adminService;

    /**
     * 新增
     */
    @PostMapping("/add")
    public Result add (@RequestBody Admin admin){
        adminService.add(admin);
        return Result.success();
    }

    /**
     * 更改
     */
    @PutMapping("/update")
    public  Result update(@RequestBody Admin admin){
        adminService.updateById(admin);
        return Result.success();
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        adminService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/batch")
    public Result delete(@RequestBody List<Integer> ids) {
        adminService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 查询所有
     * @param admin
     * @return
     */
    @GetMapping("/selectAll")
    public Result selectAll(Admin admin){
//        接受 admin 参数 返回很多个对象 用一个list包着
        List<Admin> list = adminService.selectAll(admin);
        return Result.success(list);
    }

    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Account account){
//        需要判断角色
        if (RoleEnum.ADMIN.name().equals(account.getRole())){
            adminService.updatePassword(account);
        }
        return Result.success();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id){
        Admin admin = adminService.selectById(id);
        return Result.success(admin);
    }

    /**
     * 分页查询
     * @param admin
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/selectPage")
    //    前端传入参数用@RequestParam
    public Result selectPage(Admin admin,
                        @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize){
        PageInfo<Admin> pageInfo = adminService.selectPage( admin, pageNum,pageSize);
//        带有分页数据的返回到前台
        return Result.success(pageInfo);
    }

}
